package com.thinkit.bigdata.web.controller.perCenter;

import com.google.common.base.Strings;
import com.thinkit.bigdata.core.util.FtpUtil;
import com.thinkit.bigdata.core.util.ProjectPubMet;
import com.thinkit.bigdata.core.util.StringUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.es.audioEs.Source;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.service.perCenter.PerCenDetService;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 待办任务详情
 * Created by hccl on 2018/9/5.
 */
@RestController
@RequestMapping("/pending-task-detail")
public class PendingTaskDetail {

    private static Logger logger = Logger.getLogger(PendingTaskDetail.class);

    @Resource
    private PerCenDetService perCenDetService;

    @Resource
    private ESUtil esUtil;

    @Resource
    private ProjectPubMet pubMet;

    @RequestMapping(value = "/get-workScore-serialNumber", method = RequestMethod.POST)
    public HtmlResult getWorkScoreSerialNumber(HttpServletRequest request) {
        String logTxt = "【获取任务分数】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String workId = request.getParameter("workId");//任务id
        String taskType = request.getParameter("taskType");//录音流水
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "taskType = " + taskType);
        try {
            return perCenDetService.getWorkScoreSerialNumber(request);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "获取任务分数失败");
        }
    }

    @RequestMapping(value = "/get-audio-mgs", method = RequestMethod.POST)
    public HtmlResult getAudioMes(HttpServletRequest request) {
        String logTxt = "【获取随录信息方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        logger.info(logTxt + "serialNumber = " + serialNumber);
        try {
            return perCenDetService.getDataBySerialNumber(serialNumber);
        } catch (IOException e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "获取随录信息失败");
        }
    }

    /**
     * 判断文件是否存在
     */
    @ResponseBody
    @RequestMapping("/is-audio-exists")
    public HtmlResult isAudioExists(HttpServletRequest request) {
        String logTxt = "【判断文件是否存在】";
        String serialNumber = request.getParameter("serialNumber");//录音流水
        logger.info("【es-Crud】" + SystemStatic.crud.toString());
        String mgs = SystemStatic.crud.get(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, serialNumber);
        Source source = esUtil.str2entity(mgs);
        //文件地址路径
        String audioUrl = source.getAudioPath();
        String ftpPath = audioUrl.substring(0, audioUrl.lastIndexOf(StringUtil.FILESEPARATOR));
        String fileName = audioUrl.substring(audioUrl.lastIndexOf(StringUtil.FILESEPARATOR) + 1);
        //todo优化录音下载到本地的路径 省份-班组-工号!!!!
        String voicePath = source.getVoiceInfo().getProvinceCode() + StringUtil.FILESEPARATOR
                + source.getVoiceInfo().getGroupId() + StringUtil.FILESEPARATOR
                + source.getVoiceInfo().getSeatId() + StringUtil.FILESEPARATOR;
        String localPath = SystemStatic.SYSTEM_USER_PATH_AUDIO + voicePath ;
        logger.info(logTxt + "ftpPath = " + ftpPath);
        logger.info(logTxt + "fileName = " + fileName);
        logger.info(logTxt + "localPath = " + localPath);
        File file = new File(localPath + StringUtil.FILESEPARATOR + fileName);
        if (file.exists()) {
            logger.info(logTxt + localPath + StringUtil.FILESEPARATOR + fileName + "存在");
            return HtmlResult.success(localPath + StringUtil.FILESEPARATOR + fileName);
        }
        logger.info(logTxt + audioUrl + "本地不存在，从ftp下载");
        FtpUtil ftpUtil = pubMet.getFtpUtilByArea(source.getVoiceInfo().getProvinceCode());
        if (ftpUtil.isExsits(ftpPath + "/" + fileName)) {
            if (ftpUtil.downloadFile(ftpPath, localPath, fileName))  {
                return HtmlResult.success(localPath + StringUtil.FILESEPARATOR + fileName);
            }
        }
        ftpUtil.disconnect();
        return HtmlResult.failure("语音文件不存在");
    }

    /**
     * 获取固定音频语音模型输出流
     * @param request -
     * @param response -
     */
    @RequestMapping("/get-audio-io")
    public void getPracticeWav(HttpServletRequest request, HttpServletResponse response) {
        //文件地址路径
        String audioUrl = request.getParameter("audioUrl");
        String logTxt = "获取语音输出流";
        logger.info("【" + logTxt + "】audioUrl = " + audioUrl);
        File file = new File(audioUrl);
        if(file.exists()&&file.isFile()){
            response.reset();
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                response.setHeader("Content-Disposition",
                        "attachment; filename=" +
                                new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
                logger.info("【" + logTxt + "】将文件返回页面");
                response.setContentType("application/octet-stream; charset=utf-8");
                InputStream inStream = new FileInputStream(file);
                byte[] b = new byte[1024*5];
                int len;
                while ((len = inStream.read(b)) > 0){
                    response.getOutputStream().write(b, 0, len);
                    os.flush();
                }
                inStream.close();
                os.flush();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try{
                    if (os != null) {
                        os.close();
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping(value = "/get-work-status-bu-id", method = RequestMethod.POST)
    public HtmlResult getWorkStatusById(HttpServletRequest request) {
        String logTxt = "【根据任务id获取任务状态】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String workId = request.getParameter("workId");
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "workId = " + workId);
        try {
            return perCenDetService.getWorkStatusById(request);
        } catch (IOException e) {
            e.printStackTrace();
            return HtmlResult.failure("任务状态获取失败");
        }
    }

    @RequestMapping(value = "/get-stt-info", method = RequestMethod.POST)
    public HtmlResult getSttInfo(HttpServletRequest request) {
        String logTxt = "【获取转写结果信息方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        logger.info(logTxt + "serialNumber = " + serialNumber);
        try {
            return perCenDetService.getSttInfoBySerialNumber(serialNumber);
        } catch (IOException e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "获取转写结果失败");
        }
    }

    @RequestMapping(value = "/get-tag-list", method = RequestMethod.POST)
    public HtmlResult getTags(HttpServletRequest request) {
        String logTxt = "【获取标签方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        logger.info(logTxt + "serialNumber = " + serialNumber);
        try {
            return perCenDetService.getTagsBySerialNumber(serialNumber);
        } catch (IOException e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "获取标签信息失败");
        }
    }

    @RequestMapping(value = "/get-rule-list", method = RequestMethod.POST)
    public HtmlResult getRuleList(HttpServletRequest request) {
        String logTxt = "【获取规则方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String workId = request.getParameter("workId");//质检任务Id
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "workId = " + workId);
        try {
            return perCenDetService.getRulesBySerialNumber(serialNumber, workId);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "获取规则信息失败");
        }
    }

    @RequestMapping(value = "/add-tag", method = RequestMethod.POST)
    public HtmlResult addTag(HttpServletRequest request) {
        String logTxt = "【添加标签方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String tagIds = request.getParameter("tagIds");//标签ids
        String tagNames = request.getParameter("tagNames");//标签ids
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "tagIds = " + tagIds);
        logger.info(logTxt + "tagNames = " + tagNames);
        try {
            return perCenDetService.addTag(serialNumber, tagIds, tagNames);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "添加标签信息失败");
        }
    }

    @RequestMapping(value = "/del-tag", method = RequestMethod.POST)
    public HtmlResult delTag(HttpServletRequest request) {
        String logTxt = "【删除标签方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String tagName = request.getParameter("tagName");//标签ids
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "tagName = " + tagName);
        try {
            return perCenDetService.delTag(serialNumber, tagName);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "删除标签信息失败");
        }
    }

    @RequestMapping(value = "/get-tags-online", method = RequestMethod.POST)
    public HtmlResult getTagsList(HttpServletRequest request) {
        String logTxt = "【获取全部标签方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        logger.info(logTxt + "serialNumber = " + serialNumber);
        try {
            return perCenDetService.getTagsList(serialNumber);
        } catch (IOException e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "获取全部标签信息失败");
        }
    }

    @RequestMapping(value = "/update-rules-sys", method = RequestMethod.POST)
    public HtmlResult updateRules(HttpServletRequest request) {
        String logTxt = "【系统-质检规则申诉、复检方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String workId = request.getParameter("workId");//录音流水
        String resMap = request.getParameter("resMap");
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "resMap = " + resMap);
        try {
            return perCenDetService.updateRulesForSys(request);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "系统-质检规则申诉、复检异常");
        }
    }

    @RequestMapping(value = "/get-rule-tree", method = RequestMethod.POST)
    public HtmlResult getTree(@RequestParam(value = "workId") String workId) {
        String logTxt = "【人工质检-规则-获取】";
        logger.info(logTxt);
        logger.info(logTxt + "workId = " + workId);
        if (Strings.isNullOrEmpty(workId)) {
            return HtmlResult.failure();
        }
        return perCenDetService.getTree(workId);
    }

    @RequestMapping(value = "/get-rule-by-tree", method = RequestMethod.POST)
    public HtmlResult getRuleByTree(HttpServletRequest request) {
        String logTxt = "【根据tree获取规则信息】";
        logger.info(logTxt);
        String pageNum = request.getParameter("pageNum");//起始页
        String pageSize = request.getParameter("pageSize");//每页条数
        String workId = request.getParameter("workId");//每页条数
        String modelId = request.getParameter("modelId");//每页条数
        String ruleTypeId = request.getParameter("ruleTypeId");//每页条数
        String ruleName = request.getParameter("ruleName");//每页条数
        logger.info(logTxt + "pageNum = " + pageNum);
        logger.info(logTxt + "pageSize = " + pageSize);
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "modelId = " + modelId);
        logger.info(logTxt + "ruleTypeId = " + ruleTypeId);
        logger.info(logTxt + "ruleName = " + ruleName);
        return perCenDetService.getRuleByTree(request);
    }

    @RequestMapping(value = "/add-rules-arti", method = RequestMethod.POST)
    public HtmlResult addRules(HttpServletRequest request) {
        String logTxt = "【质检员人工质检方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String workId = request.getParameter("workId");
        String modelId = request.getParameter("modelId");//规则ids
        String ruleId = request.getParameter("ruleId");//规则ids
        String proNote = request.getParameter("proNote");//处理原因
        String resMap = request.getParameter("resMap");//命中开始时间结束时间段 集合
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "modelId = " + modelId);
        logger.info(logTxt + "ruleId = " + ruleId);
        logger.info(logTxt + "proNote = " + proNote);
        logger.info(logTxt + "resMap = " + resMap);
        try {
            return perCenDetService.addRulesForArti(request);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "数据添加异常");
        }
    }

    @RequestMapping(value = "/del-judge-rules-arti", method = RequestMethod.POST)
    public HtmlResult delRules(HttpServletRequest request) {
        String logTxt = "【质检员人工质检删除方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String workId = request.getParameter("workId");//模型ids
        String modelId = request.getParameter("modelId");//模型ids
        String ruleId = request.getParameter("ruleId");//规则ids
        String detailNum = request.getParameter("detailNum");//序号
        String postType = request.getParameter("postType");//
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "modelId = " + modelId);
        logger.info(logTxt + "ruleId = " + ruleId);
        logger.info(logTxt + "detailNum = " + detailNum);
        logger.info(logTxt + "postType = " + postType);
        try {
            return perCenDetService.delRulesForArti(request);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "数据添加异常");
        }
    }

    @RequestMapping(value = "/is-rules-exit", method = RequestMethod.POST)
    public HtmlResult isRuleExit(HttpServletRequest request) {
        String logTxt = "【判断以有规则方法】";
        logger.info(logTxt);
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String workId = request.getParameter("workId");//任务Id
        String resMap = request.getParameter("resMap");//命中开始时间结束时间段 集合
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "resMap = " + resMap);
        try {
            return perCenDetService.isRuleExit(request);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure(logTxt + "请求异常");
        }
    }
}
